package com.tom.tommessenger3;

import static com.tom.tommessenger3.CommonUtilities.DISPLAY_MESSAGE_ACTION;
import static com.tom.tommessenger3.CommonUtilities.EXTRA_MESSAGE;

import com.tom.tommessenger3.Message;
import com.tom.tommessenger3.db.MessageDBOpenHelper;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList; 
import java.util.List;
import java.util.Locale;

import android.database.Cursor;

import java.util.Date;
import java.text.SimpleDateFormat;

/**
 * @author salva
 *
 */
public class MessageHistoryActivity extends Activity {

	Drawable[] usrimg=null;
	String bgimg = "", _user="", _pass="";
	int odd_resID,even_resID;
	ListView myList;
	private MyCustomAdapter mConverationAdapter = new MyCustomAdapter();
	private ArrayList<Message> mConversationList = null;
	private Cursor mCursor = null;
	private MessageDBOpenHelper mDbOpenHelper;
	private Message mConversationItem = null;
	
	private final BroadcastReceiver mHandleMessageReceiver =
            new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);

            Message m = new Message(newMessage);
            Log.i(TAG, "incoming message");
            
            // last salva
            //long success = mDbOpenHelper.insertColumn(m);
            //String result = "Insert Column " + m.getsenderNumber() + ": success-" + success;
            //Log.i(TAG, result);
            
            //mAdapter.add(m);
        	//mAdapter.notifyDataSetChanged();
        	
        	/*String suppressed_msg = m.getmsgBody().substring(0, Math.min(m.getmsgBody().length(), 18)) + "...";
        	CommonUtilities.generateNotification(context, suppressed_msg);
        	
        	updateSenderListViewFromDB();*/
    		updateConversionFromDB(m.getsenderNumber());
    		myList.setSelection(mConverationAdapter.getCount() - 1);

        }
    };
	
	private static final String TAG = "MsgHistoryActivity";
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_message_history);
		
		this.mConversationList = new ArrayList<Message>();
		//finding the list view
		myList = (ListView)findViewById(R.id.myList);
		myList.setAdapter(mConverationAdapter);
		myList.setCacheColorHint(0);
	
	    // DB Create and Open
        mDbOpenHelper = new MessageDBOpenHelper(this);
        mDbOpenHelper.open();
        
		Intent intent = getIntent();
		String sender_number = intent.getStringExtra(Message.SENDER_NUMBER);
		
		
		updateConversionFromDB(sender_number);
		myList.setSelection(mConverationAdapter.getCount() - 1);
	}
	
	@Override
	public void onResume() {
		super.onResume();
		Log.i(TAG, "onResume started.");
		
		registerReceiver(mHandleMessageReceiver,
                new IntentFilter(DISPLAY_MESSAGE_ACTION));
	}
	
	
	/**
	 * This class serves as the adapter that draws rows and provides data to the list 
	 * @author aman
	 *
	 */
	class MyCustomAdapter extends BaseAdapter {
		/**
		 * returns the count of elements in the Array that is used to draw the text in rows 
		 * @see android.widget.Adapter#getCount()
		 */
		@Override
		public int getCount() {
			return mConversationList.size();
		}

		/**
		 * Get the data item associated with the specified position in the data set.
		 * (not Implemented at this point)
		 * @param position The position of the row that was clicked (0-n)
		 * @see android.widget.Adapter#getItem(int)
		 */
		@Override
		public String getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		/**
		 * Get the row id associated with the specified position in the list.
		 * (not implemented at this point)
		 * @param position The position of the row that was clicked (0-n)
		 * @see android.widget.Adapter#getItemId(int)
		 */
		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		/**
		 * Returns the complete row that the System draws.
		 * It is called every time the System needs to draw a new row;
		 * You can control the appearance of each row inside this function.
		 * @param position The position of the row that was clicked (0-n)
		 * @param convertView The View object of the row that was last created. null if its the first row
		 * @param parent The ViewGroup object of the parent view
		 * @see android.widget.Adapter#getView(int, android.view.View, android.view.ViewGroup)
		 */

		public View getView(int position, View convertView, ViewGroup parent) {
			LayoutInflater inflater = getLayoutInflater();
			View row;
			//SharedPreferences prefList = getSharedPreferences("PrefsFile",MODE_PRIVATE);;
			//String even_color = prefList.getString("even_bubble_color","pink");
			//String odd_color = prefList.getString("odd_bubble_color","green");
			//int even_color_id=getResources().getIdentifier(even_color,"drawable","com.teks.chilltwit"),
			//	odd_color_id=getResources().getIdentifier(odd_color,"drawable","com.teks.chilltwit");
			//ImageView even_view,odd_view;
			//System.out.println("Timeline: Position: "+position+", Length: "+data.length);
			//if(position!=data.length-1){
			//if(position%2==0){
				row = inflater.inflate(R.layout.list_row_layout_even, parent, false);
				TextView textLabel = (TextView) row.findViewById(R.id.text);
				
				String aConversation = mConversationList.get(position).getmsgBody() + "\n" + 
						mConversationList.get(position).getsenderNumber();
				textLabel.setText(aConversation);//mConversationList.get(position).getmsgBody());//ndata[position]);
				
				TextView timestamp = (TextView) row.findViewById(R.id.conv_timestamp);
				//timestamp.setText(mConversationList.get(position).getissueDate());
				//String message = getString(R.string.am);
				Date d = mConversationList.get(position).getissueDateObject();
				SimpleDateFormat formatter = new SimpleDateFormat ( "hh:mm", Locale.KOREA );
		        String time_str = formatter.format(d); 
		        if(d.getHours() >= 12 )
		        	timestamp.setText(getString(R.string.pm_time, time_str));
		        else
		        	timestamp.setText(getString(R.string.am_time, time_str));
		      		      
			//}
			/*
			 else{
				row = inflater.inflate(R.layout.list_row_layout_odd, parent, false);
				TextView textLabel = (TextView) row.findViewById(R.id.text);
				
				textLabel.setText(mConversationList.get(position).getmsgBody());//data[position]);
			}
			*/
				
			return (row);
		}
	}
	
	
	private void updateConversionFromDB(String senderNumber){
        mCursor = null;
        mCursor = mDbOpenHelper.getMatchColumns(Message.SENDER_NUMBER, senderNumber);
        Log.e("MessageHistoryAcitvity", "Message DB COUNT = " + mCursor.getCount());
         
        while (mCursor.moveToNext()) {
  
        	this.mConversationItem = new Message(
        			mCursor.getLong(mCursor.getColumnIndex("_id")),
        			mCursor.getString(mCursor.getColumnIndex(Message.SENDER_NAME)),
        			mCursor.getString(mCursor.getColumnIndex(Message.SENDER_NUMBER)),
        			mCursor.getString(mCursor.getColumnIndex(Message.MESSAGE_BODY)),
        			mCursor.getString(mCursor.getColumnIndex(Message.ISSUE_DATE)));
        	//mConverationAdapter.add(mConversationItem);
            //mInfoArray.add(mInfoClass);
        	mConversationList.add(mConversationItem);
        }
        
        mConverationAdapter.notifyDataSetChanged();
        mCursor.close();
    }
	

	/////////////////////////////////////////////////////////////
	
}